<?php
// +----------------------------------------------------------------------
// | HisiPHP框架[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2021 http://www.hisiphp.com
// +----------------------------------------------------------------------
// | HisiPHP承诺基础框架永久免费开源，您可用于学习和商用，但必须保留软件版权信息。
// +----------------------------------------------------------------------
// | Author: 橘子俊 <364666827@qq.com>，开发者QQ群：50304283
// +----------------------------------------------------------------------

// 为方便系统升级，二次开发中用到的公共函数请写在此文件，禁止修改common.php文件
// ===== 系统升级时此文件永远不会被覆盖 =====
require_once 'constant.php';

use think\Db;
use think\facade\Env;
//use GuzzleHttp\Client;
use app\common\service\Factory;

/**
 * 文件上传路径规则
 *
 * @author KING
 * @date 2020年7月21日
 *
 * @return string
 */
function uploadDate() {
	return date('Ym') . DIRECTORY_SEPARATOR . date('d') . DIRECTORY_SEPARATOR . md5(microtime(true));
}

/**
 * 格式化显示时间
 *
 * @author KING
 * @date 2020年7月22日
 *
 * @param integer $timestamp
 * @param string $format
 * @param string $default
 * @return string
 */
function mimoDate($timestamp, $format='Y-m-d H:i:s', $default='') {
	if (empty($timestamp)) return $default;
	else return date($format, $timestamp);
}

/**
 * 记录日志
 * $data 日志信息(字符串或数组或对象)
 * $logName 日志文件名
 * $close 是否关闭记录
 */
if(!function_exists('addLog')){
	function addLog($msg, $fileName = '', $format=true)
	{
		$logDir = env('runtime_path') . 'log/' . date('Ym') . '/'. date('d') . '/';

		if (!file_exists($logDir)) {
			@mkdir($logDir, 0777, true);
		}

		if ($fileName == '') {
			$filename = $logDir . 'default.log';
		} else {
			$filename = $logDir . $fileName . '.log';
		}

		if ($format) {
			$dateLine = '[' . date('Y-m-d H:i:s') . "]";
			$msgLine = (is_array($msg) ? print_r($msg, true) : $msg) . "\n";

			$all = $dateLine . $msgLine;
		} else {
			$all = $msg;
		}

		@file_put_contents($filename, $all, FILE_APPEND);
	}
}

/**
 * 控制台打印
 *
 * @author KING
 * @date 2020年5月14日
 *
 * @param mix $msg
 * @param string $flag
 * @param string $format
 */
function consoleLog($msg, $flag='', $format=true) {
	$msg = (is_array($msg) ? print_r($msg, true) : $msg);
	$msg = ($flag ? "[".$flag."] ":'').$msg;
	if ($format) {
		$msg = "[".date('Y-m-d H:i:s')."]".$msg."\n";
	}
	echo $msg;
}

/**
 * 格式化秒显示
 *
 * @author KING
 * @date 2020年6月10日
 *
 * @param unknown $sec
 * @param string $showSecond
 * @return string
 */
function formatSecond($sec, $showSecond=false){
	if(!$sec) return '0';
	$negative = '';
	if($sec < 0) $negative = '-';
	$sec = abs($sec);
	$d = floor($sec / 86400);
	$tmp = $sec % 86400;
	$h = floor($tmp / 3600);
	$tmp %= 3600;
	$m = floor($tmp /60);
	$s = $tmp % 60;
	$result = '';
	if($d) $result.=$d.'天';
	if($h) $result.=$h.'时';
	if($m) $result.=$m.'分';
	if ($showSecond) {
		$result = $sec.'秒';
	}
	return $negative.$result;
}

/**
 * 判断日期格式是否正确
 *
 * @author KING
 * @date 2018年12月1日
 *
 * @param string $str
 * @param string $format
 * @return boolean
 */
function isDateTime($str, $format='Y-m-d H:i:s'){
	$unixTime_1=strtotime($str);
	if(!is_numeric($unixTime_1)) return false; //如果不是数字格式，则直接返回
	$checkDate=date($format,$unixTime_1);
	$unixTime_2=strtotime($checkDate);
	if($unixTime_1==$unixTime_2){
		return true;
	}else{
		return false;
	}
}

/**
 * 从数组中获取指定键名的值
 *
 * @author KING
 * @date 2018年12月5日
 *
 * @param array $array
 * @param string $key
 * @param mix $default
 * @return string
 */
function arrayGet($array, $key, $default = null, $checkValNull = false) {
	if (!$array) return $default;
	if (is_array($array)) {
		if (isset($array[$key]) || array_key_exists($key, $array)) {
			if ($checkValNull && is_null($array[$key])) return $default;
			else return $array[$key];
		} else return $default;
	} else {
		return $default;
	}
}

/**
 * 自动识别物料类型
 *
 * @author KING
 * @date 2019年4月30日
 *
 * @param string $type
 * @param string $name
 */
function autoIdentifyType($type, $name) {

	$fabricTypeArr = ['面料'];	// 面料
	$liningTypeArr = ['里料'];	// 里料
	$accessoriesTypeArr = ['辅料'];	// 辅料
	foreach ($fabricTypeArr as $v) {
		if (mb_stripos($type, $v) !== false) {
			return 'fabric';
		}
	}
	foreach ($liningTypeArr as $v) {
		if (mb_stripos($type, $v) !== false) {
			return 'lining';
		}
	}
	foreach ($accessoriesTypeArr as $v) {
		if (mb_stripos($type, $v) !== false) {
			return 'accessories';
		}
	}
	$mTypeTagsList= db('material_type_tags')->order('order desc')->select();
	$fabric=[];$lining=[];$accessories=[];
	foreach ($mTypeTagsList as $key => $value) {
		switch ($value['type']) {
			case 'fabric':
				$fabric[]=$value['name'];
				break;
			case 'lining':
				$lining[]=$value['name'];
				break;
			case 'accessories':
				$accessories[]=$value['name'];
				break;
			default:
				break;
		}
	}
	$fabricNameArr = $fabric;	// 面料
	$liningNameArr = $lining;	// 里料
	$accessoriesNameArr = $accessories;	// 辅料
	foreach ($fabricNameArr as $v) {
		if (mb_stripos($name, $v) !== false) {
			return 'fabric';
		}
	}
	foreach ($liningNameArr as $v) {
		if (mb_stripos($name, $v) !== false) {
			return 'lining';
		}
	}
	foreach ($accessoriesNameArr as $v) {
		if (mb_stripos($name, $v) !== false) {
			return 'accessories';
		}
	}

	return '';
}

/**
 * 获取数组的第一个键名
 */
if (!function_exists('array_key_first')) {
	function array_key_first(array $arr) {
		foreach($arr as $key => $unused) {
			return $key;
		}
		return NULL;
	}
}
/**
 * 重新组织下标,返回$key键名的新数组
 */
if (!function_exists('arrayKeyVal')) {
    function arrayByKey($arr, $keyname){
        $newArr = [];
        foreach ($arr as $key => $item) {
            $newArr[$item[$keyname]]=$item;
        }
        return $newArr;
    }
}

/**
 * 下载远程图片到本地
 */
if (!function_exists('downloadPic')) {
	function downloadPic($pic, &$error='', $time=0) {
		try {

			$code = md5($pic);
			$time = $time?$time:time();
			$uploadPath0 = "upload/".date("Ym", $time)."/".date("d", $time)."/";
			$uploadPath = env('root_path').'public/'.$uploadPath0;
			if(!file_exists($uploadPath)) {
				mkdir($uploadPath, 0777, true);
			}

			$fileNameOri = @pathinfo($pic, PATHINFO_BASENAME);
			$fileNameArr = explode('?', $fileNameOri);
			$fileName = $fileNameArr ? $fileNameArr[0] : md5(random()).".jpg";
			$ext = pathinfo($fileName, PATHINFO_EXTENSION);
			$ext = $ext ? $ext : 'jpg';

			$localFile = $uploadPath . $code.'.'.$ext;

			/*
			$client = new Client();
			$response = $client->request('GET', $pic, ['save_to' => $localFile, 'verify' => false, 'timeout' => 300]);
			if($response->getStatusCode() == 200) {
				return IMG_URL.$uploadPath0.$code.'.'.$ext;
			} else {
				throw new \Exception('('.$response->getStatusCode() . ')' . $response->getReasonPhrase());
			}
			*/

			$streamOpts = [
				"ssl" => [
					"verify_peer"=>false,
					"verify_peer_name"=>false,
				]
			];
			$context = stream_context_create($streamOpts);
			$picData = file_get_contents($pic, false, $context);
			if (empty($picData)) {
				throw new \Exception('file_get_contents empty');
			} else {
				if(file_put_contents($localFile, $picData)) {
					return IMG_URL.$uploadPath0.$code.'.'.$ext;
				} else {
					throw new \Exception('file_put_contents error');
				}
			}

		} catch (\Exception $e) {
			$error = '图片下载失败，' . $e->getMessage();
			return '';
		}
	}
}

/**
 * 获取redis实例
 */
if (!function_exists('getRedis')) {
	function getRedis($options=[], $db=null) {
		global $_redis;
		$options = array_merge(config('cache.'), $options);

		$key = md5(json_encode($options).$db);
		if (isset($_redis[$key])) $handler = $_redis[$key];
		else {
			$handler = new \Redis;

			if (arrayGet($options, 'persistent')) {
				$handler->pconnect($options['host'], $options['port'], $options['timeout'], 'persistent_id_' . $options['select']);
			} else {
				$handler->connect($options['host'], $options['port'], $options['timeout']);
			}

			if ('' != $options['password']) {
				$handler->auth($options['password']);
			}

			if ($db !== null) {
				$handler->select($db);
			} elseif (0 != $options['select']) {
				$handler->select($options['select']);
			}

			$_redis[$key] = $handler;
		}
		return $handler;
	}
}

/**
 * 获取工厂键值对
 *
 * @author KING
 * @date 2020年6月20日
 *
 * @return array
 */
function getFactoryKV($isAll=true) {
	return (new \app\common\service\Factory())->getKVCache($isAll);
}

/**
 * 更新工厂缓存数据
 */
function updateFactoryKVCache(){
    return (new \app\common\service\Factory())->updateKVCache();
}
/**
 * 获取外发工厂键值对
 *
 * @author KING
 * @date 2020年6月20日
 *
 * @return array
 */
function getFactoryOutgoKV($status=1) {
	return (new \app\common\service\FactoryOutgo())->getKVCache($status);
}
/**
 * 获取外发工厂根据工厂分组键值对
 *
 * @author KING
 * @date 2020年6月20日
 *
 * @return array
 */
function getFactoryOutgoGbFactoryIdsKV($status=1) {
	return (new \app\common\service\FactoryOutgo())->getKVListGbFactoryIds($status);
}
/**
 * 获取管理员键值对
 *
 * @author KING
 * @date 2020年6月20日
 *
 * @return array
 */
function getSystemUserKV($status=1) {
	return (new \app\common\service\SystemUser())->getKVCache($status);
}

/**
 * 获取管理员头像键值对
 *
 * @author KING
 * @date 2020年6月20日
 *
 * @return array
 */
function getSystemUserAvatarKV($status=1) {
	return (new \app\common\service\SystemUser())->getAvatarKV($status);
}

/**
 * 获取标签用户键值对
 *
 * @author KING
 * @date 2020年7月28日
 *
 */
function getTagUserKV($tag) {
	return (new \app\common\service\SystemUser())->getTagKVCache($tag);
}

/**
 * 获取角色用户键值对
 *
 * @author KING
 * @date 2020年7月28日
 *
 */
function getRoleUserKV($role) {
	return (new \app\common\service\SystemUser())->getRoleKVCache($role);
}

/**
 * 获取员工键值对
 *
 * @author KING
 * @date 2020年6月20日
 *
 * @return array
 */
function getUserKV($status=1) {
	return (new \app\common\service\User())->getKVCache($status);
}

/**
 * 获取档口键值对
 *
 * @author KING
 * @date 2020年6月20日
 *
 * @return array
 */
function getStallsKV() {
	return (new \app\common\service\Stalls())->getKVCache();
}

/**
 * 获取次品类型键值对
 *
 * @author KING
 * @date 2020年6月20日
 *
 * @return array
 */
function getRejectsKV() {
	return (new \app\common\service\Rejects())->getKVCache();
}

function getDepartKV($factoryId=null) {
	return (new \app\common\service\Depart())->getKVCache($factoryId);
}

function getGroupKV($factoryId=0) {
	return (new \app\common\service\Group())->getKVCache($factoryId);
}

function getUnitKV() {
	return (new \app\common\service\Unit())->getKVCache();
}

function getSizeKV() {
	return (new \app\common\service\Size())->getKVCache();
}

function getPartKV() {
	return (new \app\common\service\Part())->getKVCache();
}

function getStorehouseKV() {
    return (new \app\common\service\Storehouse())->getKVCache();
}

function getStoreshelfKV($storehouseId=0) {
	return (new \app\common\service\Storeshelf())->getKVCache($storehouseId);
}

function getStockStorehouseKV() {
	return (new \app\common\service\StockStorehouse())->getKVCache();
}

function getStockStoreshelfKV($storehouseId=0) {
	return (new \app\common\service\StockStoreshelf())->getKVCache($storehouseId);
}

function getMaterialName($materialId) {
	return (new \app\common\service\Material())->getMaterialName($materialId);
}

/**
 * 获取订单标签
 *
 * @author KING
 * @date 2020年6月30日
 *
 * @param array $orderInfo
 * @param array $skuInfo
 * @return string
 */
function getOrderTag($orderInfo, $skuInfo=[]) {
	$tags = [];
	$type = $orderInfo['type'];
	$oType = $orderInfo['o_type'];
	$sku = $orderInfo['sku'];
	$isAutoImport = $orderInfo['is_auto_import'];

	if($type == 'new') $tags[] = "<img src='/static/mp/image/new.png' title='新单'/>";
	if($type == 'emergent') $tags[] = "<img src='/static/mp/image/emergent.png' title='紧急单'/>";

	/* if(in_array($oType, ['CMT', 'CMT2'])) $tags[] = "<img src='/static/mp/image/cmt.png' title='CMT'/>";
	if($oType == 'FOB') $tags[] = "<img src='/static/mp/image/fob.png' title='FOB'/>"; */

	if ($skuInfo) {
		$isPublic = arrayGet($skuInfo, 'is_public', 0);
	} else {
		$isPublic = (new \app\common\service\Sku())->getInfoBySku($sku, 'is_public');
	}
	if($isPublic == 1) $tags[] = "<img src='/static/mp/image/public.png' title='公共款'/>";

	// if(checkSkuStockBySku($sku)) $tags[] = "<img src='".base_url()."static/images/cheng.png' title='成品库存'/>";

	$omlList = (new \app\common\service\OrderMaterialLog())->getListByOrderId($orderInfo['id'], 'create_time,material_name,tiaoshu,remark', 'id asc');
	if ($omlList) {
		$tipArr = [];
		foreach ($omlList as $logK => $logV) {
			$tipArr[] = sprintf("[%s][%s] %s %s", date("m-d H:i",$logV['create_time']), $logV['material_name'], $logV['tiaoshu'], $logV['remark']);
		}
		$tips = implode("\n", $tipArr);
		$tags[] = "<img src='/static/mp/image/wu.png' title='{$tips}'/>";
	}

	$orderFrom = arrayGet(config('mimo.order_from'), $isAutoImport, '');
	if ($isAutoImport == 1) $tags[] = "<img src='/static/mp/image/mi.png' title='{$orderFrom}'/>";
	elseif ($isAutoImport == 2) $tags[] = "<img src='/static/mp/image/ming.png' title='{$orderFrom}'/>";
	elseif ($isAutoImport == 3) $tags[] = "<img src='/static/mp/image/shi.png' title='{$orderFrom}'/>";

	return $tags ? "<div class='tags'>" . implode('', $tags) . "</div>" : '';
}

/**
 * 获取PHPExcel对象
 *
 * @author King
 * @date 2020年8月11日
 *
 * @return PHPExcel
 */
function getExcelObj(){
	error_reporting(E_ALL);
	ini_set('display_errors', TRUE);
	ini_set('display_startup_errors', TRUE);

	/** Include PHPExcel */
	require_once env('root_path').'plugins/excel/phpexcel/Classes/PHPExcel.php';

	$phpExcel = new PHPExcel();
	$phpExcel->getProperties()
	->setCreator("King")
	->setLastModifiedBy("King")
	->setTitle("Office 2007 XLSX Document")
	->setSubject("Office 2007 XLSX Document")
	->setDescription("Document for Office 2007 XLSX")
	->setKeywords("office 2007");
	return $phpExcel;
}

// 数字转xls字母
function getExcelLetter($i, $s = 65) {
	$str = '';
	if (floor($i / 26) > 0) {
		$str .= getExcelLetter(floor($i / 26)-1);
	}
	return $str . chr($i % 26 + $s);
}

/**
 * 过滤0值和空值显示
 *
 * @author King
 * @date 2020年9月3日
 *
 * @param unknown $data
 * @param string $default
 * @return string|unknown
 */
function filterZero($data, $default='') {
	if ($data==0 || $data=='') return $default;
	else return $data;
}

/**
 * 根据请求uri判断权限
 *
 * @author King
 * @date 2020年9月6日
 *
 * @param string $uri
 * @param string $params
 * @return boolean
 */
function checkAuthByURI($uri, $params='') {
	return \app\system\model\SystemRole::checkAuthByURI($uri, $params);
}
/**
 * 检测一个时间段内含有几个剔除日
 * @param int $startTime
 * @param int $endTime
 * @return int
 */
function checkSunday($startTime=0,$endTime=0){
	if($startTime>$endTime)		return 0;
	$todayS=date("d",$startTime);$todayE=date("d",$endTime);
	$duoyu=$todayE-$todayS;
	$secondNum=$duoyu*10*3600;
	return $secondNum;
}
/**
 * 计算有效的节点时间 create_time除外
 * @param int $time
 * @return int
 */
function calTime($time){
	//有效到料时间
	$Day = date('Y-m-d ',$time);
	$begin = strtotime($Day."08:00".":00");
	$end = strtotime($Day."22:00".":00");
	if($time < $begin){
		$timeStart=strtotime($Day."08:00".":00");//作为开始时间则为当天8点
		$timeEnd=strtotime($Day."08:01".":00");//作为结束时间则为昨天22点
	}else if($time > $end){
		$timeStart = strtotime('+1 day 08:00:00', $time);////作为开始时间则为后一日天8点
		$timeEnd = strtotime('+1 day 08:01:00', $time);//作为结束时间则为当天天22点
	}else{
		$timeStart = $time;////作为开始时间则为后一日天8点
		$timeEnd = $time;//作为结束时间则为当天天22点
	}
	return [$timeStart,$timeEnd];
}
/**
 * 计算有效的节点时间 create_time除外
 * @param int $time
 * @return int
 */
function calCreateTime($time){
	$Day = date('Y-m-d ',$time);
	$crtimeBegin = strtotime($Day."19:00".":00");
	//$crtimeEnd = strtotime($Day."23:00".":00");
	if($time <= $crtimeBegin){
		$effCreateTime=$time;
	}else{
		$effCreateTime=strtotime($Day."23:59".":59");
	}
	return $effCreateTime;
}

function getRandomString($len, $chars=null)
{
    if (is_null($chars)){
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    }
    mt_srand(10000000*(double)microtime());
    for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
        $str .= $chars[mt_rand(0, $lc)];
    }
    return $str;
}

/**
 * 微信服务号url生成
 *
 * @author King
 * @date 2021年4月27日
 *
 * @param string $uri			跳转URI（wechat/task/index）
 * @param string|array $params		其它参数（a=13&b=321或['a'=>'13', 'b'=>'321']）
 * @param string $needLogin		是否需要登录（默认true）
 * @return string
 */
function wechatUrl($uri, $params='', $needLogin=true) {
	if ($needLogin) {
		think\facade\Url::root('/admin.php');
		return url('/wechat/AutoLogin/index?u=' . $uri, $params, '', true);
	} else {
		return url($uri, $params, '', true);
	}
}

/**
 * 获取sku款式名称
 *
 * @author King
 * @date 2021年7月7日
 *
 * @param unknown $sku
 * @return string
 */
function getStyleName($sku) {
	if ($sku == '') return '';
	$arr = ["twop" => "两个",
		"blazer" => "运动上衣",
		"blouse" => "衬衫",
		"bodysui" => "紧身衣",
		"dress" => "连衣裙",
		"Sweatsh" => "运动上衣",
		"jacket" => "夹克",
		"jumpsuit" => "连身裤",
		"kimono" => "和服",
		"legging" => "紧身裤",
		"lingerie" => "内衣",
		"matern" => "孕服",
		"night" => "睡衣",
		"twopiece" => "两件装",
		"outer" => "外套",
		"outwearr" => "外套",
		"pajama" => "睡衣",
		"pants" => "裤子",
		"short" => "知袖",
		"skirt" => "裙子",
		"sweatsh" => "运动上衣",
		"tee" => "青年装",
		"top" => "知袖上衣",
		"twop" => "两件装",
		"vest" => "背心",
		"jumpsui" => "连身裤",
		"leg" => "裤子",
		"opiece" => "两件装",
		"outwea" => "外套",
		"eatsh" => "运动上衣"];
	$result = "";
	foreach ($arr as $k => $v) {
		if (stristr($sku, $k) !== false) $result = $v;
	}
	return $result;
}

/**
 * 订单加一级
 * @param $where
 * @return bool
 * @author zhuguosen 905502314@qq.com
 * @date 2022/4/25
 */
function order_level(&$where, $table = '')
{
    if (FACTORY_IDS == '*') {
        return true;
    }
    switch (env('order_level')) {
        case 1:
            if (trim(FACTORY_IDS) == '' && SUB_FACTORY_ID <= 0) {
                $where[] = ["{$table}factory_id", '<', 0];
                return true;
            }
            if (trim(FACTORY_IDS) != '' && SUB_FACTORY_ID > 0) {
                $where[] = ['', 'EXP', Db::raw("{$table}factory_id in (" . FACTORY_IDS . ") OR FIND_IN_SET(" . SUB_FACTORY_ID . ",{$table}sub_factory_ids)")];
                return true;
            }
            if (trim(FACTORY_IDS) != '') {
                $where[] = ["{$table}factory_id", 'in', FACTORY_IDS];
            }
            // 下级工厂ID匹配
            if (SUB_FACTORY_ID > 0) {
                $where[] = ['', 'EXP', Db::raw("FIND_IN_SET(" . SUB_FACTORY_ID . ",{$table}sub_factory_ids)")];
            }
            return true;
            break;
        default:
            if (trim(FACTORY_IDS) == '') {
                $where[] = ["{$table}factory_id", '<', 0];
                return true;
            }
            if (trim(FACTORY_IDS) != '') {
                $where[] = ["{$table}factory_id", 'in', FACTORY_IDS];
                return true;
            }
            break;
    }
}

/**
 * 订单加一级--对应的工厂搜索处理
 * @param int $factorId 工厂id
 * @param $where  查询条件
 * @param string $table order表的前缀
 * @param string $type array $where为数组类型操作 查询条件
 * @return bool
 * @author zhuguosen 905502314@qq.com
 * @date 2022/5/22
 */
function factory_id_level($factorId = 0, &$where, $table = '', $type = 'array')
{
    if ($factorId == 0) {
        return true;
    }
    switch (env('order_level')) {
        case 1:
            $where[] = ['', 'EXP', Db::raw("{$table}factory_id = ({$factorId}) OR FIND_IN_SET({$factorId},{$table}sub_factory_ids)")];
            return true;
            break;
        default:
            $where[] = ["{$table}factory_id", '=', $factorId];
            break;
    }
}